//
//  RAPStatusCellPicturesView.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/2/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//  微博配图

import UIKit
import SDWebImage

/// 最大列数
private let kMaxCol = 3
/// item间距
private let kItemPadding: CGFloat = 4
/// 图片cell边长
private let itemSideLength = (kScreenBounds.width - 2 * kStatusCellMargin - 2 * kItemPadding) / CGFloat(kMaxCol)

private let kCellResueIdentifier = "RAPStatusPictureCell"

class RAPStatusCellPicturesView: UICollectionView, UICollectionViewDataSource {
    
    var pic_urls: [RAPStatusPictureModel]? {
        didSet {
            if let picURLs = pic_urls {
                countLabel.text = "\(picURLs.count)"
                
                // 计算collection view的尺寸
                self.snp_updateConstraints(closure: { (make) -> Void in
                    let size = self.calculateOverallSize(picURLs.count)
                    make.height.equalTo(size.height) //
                    make.width.equalTo(size.width)
                })
                // 刷新数据
                reloadData()
            }
        }
    }
    
    var isGIFs: [Bool]?
    
    ///  计算collection view 的size
    ///
    ///  - parameter count: 多少张配图
    ///
    ///  - returns: 计算好的size
    func calculateOverallSize(count: Int) -> CGSize {
        // 设置item 尺寸
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSizeMake(itemSideLength, itemSideLength)
        
        
        var sizeW: CGFloat = 0
        var sizeH: CGFloat = 0
        //计算行和列
        var col = 0
        var row = 0
        
        if count == 4 {
            col = 2
            row = 2
        } else if count == 1 {
            let urlKey = SDWebImageManager.sharedManager().cacheKeyForURL(NSURL(string: (pic_urls?.first?.thumbnail_pic)!))
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(urlKey)
            
            sizeW = image.size.width
            sizeH = image.size.height
            
            if sizeW < 50 { // 过窄
                sizeW = 50
                sizeH = image.size.height / image.size.width * sizeW // 不让变形
            } else if sizeW > kScreenBounds.width - 2 * kStatusCellMargin { // 过宽 
                sizeW = kScreenBounds.width - 2 * kStatusCellMargin
                sizeH = image.size.height / image.size.width * sizeW // 不让变形
            }
            
//            10  50
//            20  x = 50 * 20 / 10
            
//            10  50
//            y  100
//            y = 100 * 10 / 50
            
            if sizeH > 150 { // 过高
                sizeH = 150
//                sizeW = image.size.width / image.size.height * sizeH
            }
            
            
            flowLayout.itemSize = CGSizeMake(sizeW, sizeH)
            return CGSizeMake(sizeW, sizeH)
        } else {
            col = count > kMaxCol ? kMaxCol : count
            row = (count - 1) / kMaxCol + 1
        }
        
        sizeW = CGFloat(col) * itemSideLength + CGFloat(col - 1) * kItemPadding
        sizeH = CGFloat(row) * itemSideLength + CGFloat(row - 1) * kItemPadding
        return CGSize(width: sizeW, height: sizeH)
    }
    

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        // 默认为流水布局
        let flowLayout = UICollectionViewFlowLayout()
        // 行距和间距，以及item 尺寸
//        flowLayout.itemSize = CGSizeMake(itemSideLength, itemSideLength)
        flowLayout.minimumInteritemSpacing = kItemPadding
        flowLayout.minimumLineSpacing = kItemPadding
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupCollectionView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  设置collection view
    func setupCollectionView() {
        backgroundColor = UIColor(white: 237 / 255.0, alpha: 1)
        addSubview(countLabel)
        
        // 注册cell
        registerClass(RAPStatusPictureCell.self , forCellWithReuseIdentifier: kCellResueIdentifier)
        // 设置代理
        self.dataSource = self
        
        
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }
    
    /// 设置 计数label
    lazy var countLabel: UILabel = {
        let countLabel = UILabel(text: "", fontSize: 30, textColor: UIColor.blackColor())
        
        return countLabel
    }()
}

// MARK: - UICollectionViewDataSource
extension RAPStatusCellPicturesView {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let picURLs = pic_urls {
            return picURLs.count
        }
        return 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kCellResueIdentifier, forIndexPath: indexPath) as! RAPStatusPictureCell
        
        cell.picURL = pic_urls![indexPath.item]
        cell.isGIF = isGIFs![indexPath.item]
        
        return cell
    }
}
